/**
 * 四则运算 x 100条
 */
#include <stdio.h>
#include <stdlib.h>
#include "../Utils/FileIOUtils.h"
#include "../Utils/Random.h"

static const char *FILE_WRITE_PATH = "../Read_Write_Test/3.四则运算生成.txt";
static const char *FILE_WRITE_RESULT_PATH = "../Read_Write_Test/3.四则运算结果.txt";
static const char opts[4] = {'+', '-', '*', '/'};
//static const char * const opts = "+-*/";

void write_caculate_100();
void read_file_caculate_write();

int main() {
    //1.生成100条四则运算
//    write_caculate_100();
    //2.读取四则运算&计算&重新写出结果
    read_file_caculate_write();
    return EXIT_SUCCESS;
}

//1.生成100条四则运算
void write_caculate_100() {
    int a, b;
    char c;
    char *p = malloc(sizeof(char) * 15);
    FILE *file = file_open_w(FILE_WRITE_PATH);
    for (int i = 0; i < 100; ++i) {
        a = getRandom() % 10 + 1;
        b = getRandom() % 10 + 1;
        c = opts[getRandom() % 4];
        int len = sprintf(p, "%03d.%d%c%d=\n", i + 1, a, c, b);
        int v0 = file_puts(p, file);
    }
    free(p);
    file_close(file);
    printf("1.生成100条四则运算完成: %s\n", FILE_WRITE_PATH);
}

//2.读取四则运算&计算&重新写出结果
void read_file_caculate_write() {
    FILE *readFile = file_open_r(FILE_WRITE_PATH);
    FILE *writeFile = file_open_w(FILE_WRITE_RESULT_PATH);
    int num, a, b, sum;
    char c;
    char *p = malloc(sizeof(char) * 15);
    while (file_gets(p, 15, readFile)) {
        int v1 = sscanf(p, "%03d.%d%c%d=\n", &num, &a, &c, &b);
        switch (c) {
//            case opts[0]:       //编译不通过
//            case *(opts + 0):   //编译不通过
            case '+':
                sum = a + b;
                break;
            case '-':
                sum = a - b;
                break;
            case '*':
                sum = a * b;
                break;
            case '/':
                sum = a / b;
                break;
        }
        int len = sprintf(p, "%03d.%d%c%d=%d\n", num, a, c, b, sum);
        int v2 = file_puts(p, writeFile);
    }
    free(p);
    file_close(readFile);
    file_close(writeFile);
    printf("2.读取四则运算&计算&重新写出结果: %s\n", FILE_WRITE_RESULT_PATH);
}